package com.srwl.mytx.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.srwl.easeui.widget.MyTitleBar;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.ClickUtil;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.ConfirmDialog;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ModifyPhoneNumberActivity extends BaseActivity implements View.OnClickListener {
    public static final String PHONE_NUMBER = "phoneNumber";
    private static final int TIME_COUNTING = 3;
    private static final int STOP_COUNT = 4;//结束倒计时
    private static final int PHONE_NUMBER_BEUSED = 5;
    private static final String TAG = ModifyPhoneNumberActivity.class.getSimpleName();
    private String oldPhoneNumber;

    Button btn_save;
    Button btn_sendSMSCode;
    MyTitleBar titleBar;
    EditText et_password;
    EditText et_phoneNumber;
    EditText et_SMSCode;
    RelativeLayout rl_SMSCode;
    private ImageView iv_hide;
    private ImageView iv_show;
    private String str_phoneNumber;
    TimerTask task;
    Timer timer;
    int count = 120;//发送短信 等待读秒时间
    TextView tv_forgetPassWord;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case TIME_COUNTING:
                    btn_sendSMSCode.setText("" + count);
                    break;
                case STOP_COUNT:
                    btn_sendSMSCode.setText("重新获取");
                    btn_sendSMSCode.setEnabled(true);
                    break;
                case PHONE_NUMBER_BEUSED:
                    tv_forgetPassWord.setVisibility(View.VISIBLE);
                    break;
            }

            super.handleMessage(msg);
        }
    };


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modify_phone_number);

        titleBar = findViewById(R.id.title_bar);
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        initView();
    }

    private void initView() {

        btn_save = findViewById(R.id.btn_save);
        btn_sendSMSCode = findViewById(R.id.btn_send_mobile_code);
        et_password = findViewById(R.id.et_password);
        et_phoneNumber = findViewById(R.id.et_phone_number);
        et_SMSCode = findViewById(R.id.et_mobile_code);
        rl_SMSCode = findViewById(R.id.rl_sms_code);
        oldPhoneNumber = getIntent().getStringExtra(PHONE_NUMBER);
//        if (oldPhoneNumber != null) {
//            et_phoneNumber.setText(oldPhoneNumber);
//            et_phoneNumber.setSelection(et_phoneNumber.getText().length());
//        }
        tv_forgetPassWord = findViewById(R.id.tv_forget_pass_word);
        iv_hide = findViewById(R.id.iv_hide);
        iv_show = findViewById(R.id.iv_show);
        initTextChangeListener();

        iv_hide.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                iv_hide.setVisibility(View.INVISIBLE);
                iv_show.setVisibility(View.VISIBLE);
                et_password
                        .setTransformationMethod(HideReturnsTransformationMethod
                                .getInstance());
                // 切换后将EditText光标置于末尾
                CharSequence charSequence = et_password.getText();
                if (charSequence instanceof Spannable) {
                    Spannable spanText = (Spannable) charSequence;
                    Selection.setSelection(spanText, charSequence.length());
                }

            }

        });
        iv_show.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                iv_show.setVisibility(View.INVISIBLE);
                iv_hide.setVisibility(View.VISIBLE);
                et_password
                        .setTransformationMethod(PasswordTransformationMethod
                                .getInstance());
                // 切换后将EditText光标置于末尾
                CharSequence charSequence = et_password.getText();
                if (charSequence instanceof Spannable) {
                    Spannable spanText = (Spannable) charSequence;
                    Selection.setSelection(spanText, charSequence.length());
                }
            }

        });


        rl_SMSCode.setVisibility(View.VISIBLE);
        btn_sendSMSCode.setOnClickListener(this);
        tv_forgetPassWord.setOnClickListener(this);
        btn_save.setOnClickListener(this);

    }

    private void initTextChangeListener() {
        et_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (et_password.getCurrentTextColor() == Color.RED) {
                    et_password.setTextColor(getResources().getColor(R.color.text_black));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        et_phoneNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (et_phoneNumber.getCurrentTextColor() == Color.RED) {
                    et_phoneNumber.setTextColor(getResources().getColor(R.color.text_black));
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        et_SMSCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (et_SMSCode.getCurrentTextColor() == Color.RED) {
                    et_SMSCode.setTextColor(getResources().getColor(R.color.text_black));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_send_mobile_code:
                SendSMSCode();
                break;
            case R.id.btn_save:
                ReplacePhoneNumber();
                break;
            case R.id.tv_forget_pass_word:
                startActivity(new Intent(ModifyPhoneNumberActivity.this, ReplacePassWordActivity.class));
                break;
        }
    }


    private void SendSMSCode() {
        if (ClickUtil.isFastClick()) {
            return;
        }

        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString( R.string.network_unavailable));
            return;
        }
        hideSoftKeyboard();
        btn_sendSMSCode.setEnabled(false);
        str_phoneNumber = et_phoneNumber.getText().toString().trim();
        //检查输入的是否是11位数字，因为号段多变，检查是否是一个手机号，放服务端执行

        if (TextUtils.isEmpty(str_phoneNumber)) {

            btn_sendSMSCode.setEnabled(true);
            et_phoneNumber.setHint("手机号码不能为空");
            Utils.editViewValueErrorAnimate(et_phoneNumber, this);
            et_phoneNumber.setPadding(Utils.dpToPx(90, this), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效
            return;
        }

        if (!Utils.checkMobileNum(str_phoneNumber)) {
            btn_sendSMSCode.setEnabled(true);
            et_phoneNumber.setTextColor(Color.RED);
            showToast(btn_sendSMSCode, "手机号格式有误，请重新输入");
            Utils.editViewValueErrorAnimate(et_phoneNumber, this);
            et_phoneNumber.setPadding(Utils.dpToPx(90, this), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效
            return;
        }
        if (str_phoneNumber.equals(oldPhoneNumber)) {
            //是否已经绑定
            btn_sendSMSCode.setEnabled(true);
            showToast(btn_sendSMSCode, "当前就是绑定的该号码,无须更换");
            Utils.editViewValueErrorAnimate(et_phoneNumber, this);
            et_phoneNumber.setPadding(Utils.dpToPx(90, this), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效
            return;
        }

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在查询手机号是否被使用...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.show();

        RetrofitManager.getInstance()
                .createRequest(UserService.class)
                .sendMobileCode(str_phoneNumber)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressDialog.dismiss();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            showToast(btn_save, getString(R.string.system_busy));
                            btn_sendSMSCode.setEnabled(true);
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "发送信息出错" + result.getMsg());
                            switch (result.getStatus()) {
                                case Constant.SEND_MOBILE_CODE_FAIL_HAVE_NO_COUNT:
                                    showToast(btn_save, String.format(getString(R.string.send_mobile_code_remain_time), result.getData().toString()));
                                    btn_sendSMSCode.setEnabled(true);
                                    break;
                                case Constant.SEND_MOBILE_CODE_FAIL_ENGAGED:
                                    showToast(btn_save, getString(R.string.phone_number_engaged));
                                    tv_forgetPassWord.setVisibility(View.VISIBLE);
                                    btn_sendSMSCode.setEnabled(true);
                                    et_phoneNumber.setTextColor(Color.RED);
                                    break;

                                case Constant.PHONE_NUMBER_FORMAT_ERROR:
                                    showToast("手机号格式错误");
                                    btn_sendSMSCode.setEnabled(true);
                                    et_phoneNumber.setTextColor(Color.RED);
                                    return;
                            }

                            return;
                        }
                        startCount();
                        showToast(btn_save, getString(R.string.SMScode_sended));
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressDialog.dismiss();
                        btn_sendSMSCode.setEnabled(true);
                        showToast(btn_save, getString(R.string.system_busy));
                        Log.e(TAG, "发送信息出错" + t.getMessage());
                    }
                });
    }


    private void ReplacePhoneNumber() {
        hideSoftKeyboard();
        btn_save.setEnabled(false);
        String str_password = et_password.getText().toString().trim();
        String str_SMSCode = et_SMSCode.getText().toString().trim();
        final String str_phoneNumber = et_phoneNumber.getText().toString().trim();

        if (TextUtils.isEmpty(str_password)) {
            btn_save.setEnabled(true);
            et_password.setHint("登录密码不能为空");
            Utils.editViewValueErrorAnimate(et_password, this);
            et_password.setPadding(Utils.dpToPx(90, this), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效

            return;
        }
        if (str_password.length() < 6) {
            et_password.setTextColor(Color.RED);
            btn_save.setEnabled(true);
            showToast(btn_save, "密码不足6位");
            Utils.editViewValueErrorAnimate(et_password, this);
            et_password.setPadding(Utils.dpToPx(90, this), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效

            return;
        }
        if (TextUtils.isEmpty(str_phoneNumber)) {
            btn_save.setEnabled(true);
            et_phoneNumber.setHint("手机号码不能为空");
            Utils.editViewValueErrorAnimate(et_phoneNumber, this);
            et_phoneNumber.setPadding(Utils.dpToPx(90, this), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效

            return;
        }

        if (!Utils.checkMobileNum(str_phoneNumber)) {
            btn_save.setEnabled(true);
            et_phoneNumber.setTextColor(Color.RED);
            showToast(btn_save, "手机号格式有误，请重新输入");
            Utils.editViewValueErrorAnimate(et_phoneNumber, this);
            et_phoneNumber.setPadding(Utils.dpToPx(90, this), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效

            return;
        }
        if (str_phoneNumber.equals(oldPhoneNumber)) {
            //是否已经绑定
            btn_save.setEnabled(true);
            showToast(btn_save, "当前就是绑定的该号码,无须更换");
            Utils.editViewValueErrorAnimate(et_phoneNumber, this);
            et_phoneNumber.setPadding(Utils.dpToPx(90, this), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效
            return;
        }

        if (TextUtils.isEmpty(str_SMSCode)) {
            btn_save.setEnabled(true);
            et_SMSCode.setHint("验证码不能为空");
            Utils.editViewValueErrorAnimate(et_SMSCode, this);
            et_SMSCode.setPadding(Utils.dpToPx(90, this), 0, 0, 0); //至少4.4 版本设置hint 后，padding 会失效
            return;
        }


        final ProgressDialog pd = new ProgressDialog(this);
        pd.setMessage("正在更新信息...");
        pd.setCanceledOnTouchOutside(false);
        pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pd.show();
        User updateUser = new User();
        updateUser.setPhone(str_phoneNumber);
        updateUser.setPassword(str_password);
        Map<String, Object> info = new HashMap<>();
        info.put("userInfo", updateUser);
        info.put("mobileCode", str_SMSCode);

        RetrofitManager.getInstance()
                .createRequest(UserService.class)
                .modifyPhoneNumber(info)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        btn_save.setEnabled(true);
                        pd.dismiss();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            showToast(btn_save, getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "更新信息出错" + result.getMsg());
                            switch (result.getStatus()) {

                                case Constant.MOBILE_CODE_ERROR:
                                    showToast(btn_save, getString(R.string.mobile_code_error));
                                    et_SMSCode.setTextColor(Color.RED);
                                    break;
                                case Constant.MOBILE_CODE_EXPIRE:
                                    showToast(btn_save, getString(R.string.mobile_code_expire));
                                    et_SMSCode.setTextColor(Color.RED);
                                    break;
                                case Constant.MOBILE_CODE_USED:
                                    showToast(btn_save, getString(R.string.mobile_code_used));
                                    et_SMSCode.setTextColor(Color.RED);
                                    break;

                                case Constant.PASS_WORD_WRONG:
                                    showToast(btn_save, "登录密码错误");
                                    et_password.setTextColor(Color.RED);
                                    tv_forgetPassWord.setVisibility(View.VISIBLE);
                                    break;
                                case Constant.FORBID_MODIFY_PHONE_NUMBER_24:
                                    ConfirmDialog dialog = new ConfirmDialog(ModifyPhoneNumberActivity.this, "禁止", "该账户24小时内修改过登录密码，为保护账户安全，禁止更换手机号");
                                    dialog.show();

                                    break;
                            }
                            return;
                        }
                        showToast(btn_save, "更换手机号完成");
                        UserProfileManager.getInstance().setUserPhoneNumber(str_phoneNumber);
                        setResult(RESULT_OK, new Intent().putExtra("value", str_phoneNumber));
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                finish();
                            }
                        }, 1500);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        btn_save.setEnabled(true);
                        pd.dismiss();
                        showToast(btn_save, getString(R.string.system_busy));
                    }
                });
    }

    public void startCount() {
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                if (count > 0) {
                    handler.sendEmptyMessage(TIME_COUNTING);
                    count--;
                } else {
                    timer.cancel();
                    count = 60;
                    handler.sendEmptyMessage(STOP_COUNT);

                }
            }
        };
        timer.schedule(task, 0, 1000);
    }


}
